﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using Sunyi.Project.WebPoint.Common;

namespace Sunyi.Project.WebPoint.WebControl
{
    public abstract class SqlDropDownList : DropDownList
    {
        public bool NeedAllOption
        {
            get;
            set;
        }

        public bool NeedBlankOption
        {
            get;
            set;
        }

        public string SqlCommandString
        {
            get;
            set;
        }

        protected override void OnPagePreLoad(object sender, EventArgs e)
        {
            base.OnPagePreLoad(sender, e);

            if (!Page.IsPostBack)
            {
                BindItem();
            }
        }

        protected void BindItem()
        {
            if (this.NeedBlankOption) this.Items.Add(new ListItem(string.Empty, string.Empty));
            if (this.NeedAllOption) this.Items.Add(new ListItem(WebPointGlobalConstant.All, WebPointGlobalConstant.All));

            DataTable dt = DbHelper.ExecuteCommand(this.SqlCommandString);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string itemText = dr[0].ToString();
                    string itemValue = dt.Columns.Count > 1 ? dr[1].ToString() : itemText;
                    ListItem li = new ListItem(itemText, itemValue);

                    this.Items.Add(li);
                }
            }
        }
    }
}
